import { reactive, watch } from 'vue'
import type { PropertyPanelProps, BasicForm } from '../types'
import Modeling from 'bpmn-js/lib/features/modeling/Modeling.js'

export function useBasicForm(props: PropertyPanelProps) {
  const basicForm = reactive<BasicForm>({
    id: '',
    name: '',
  })

  const handleBasicFormChange = () => {
    if (!props.currentElement || !props.modeler) return

    const modeling = props.modeler.get('modeling') as Modeling
    const element = props.currentElement
    modeling.updateModdleProperties(element, element.businessObject, {
      id: basicForm.id,
      name: basicForm.name,
    })
  }

  // 监听当前元素变化，更新表单
  watch(
    () => props.currentElement,
    (element) => {
      if (element) {
        basicForm.id = element.id
        if (element.type === 'bpmn:TextAnnotation') {
          basicForm.name = element.businessObject.text || ''
        } else {
          basicForm.name = element.businessObject.name || ''
        }
      } else {
        basicForm.id = ''
        basicForm.name = ''
      }
    },
    { immediate: true },
  )

  return {
    basicForm,
    handleBasicFormChange,
  }
}
